//
//  LoginViewController.m
//  PropertyManager
//
//  Created by TNG on 2018/7/3.
//  Copyright © 2018年 Tng. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController () <TencentSessionDelegate>


@property (strong, nonatomic) TencentOAuth * oauth;

@property (strong, nonatomic) UIImageView * img;
@property (strong, nonatomic) UITextField * phoneTextFiled;
@property (strong, nonatomic) UITextField * passwordTextfiled;
@property (strong, nonatomic) UIButton * loadBtn;
@property (strong, nonatomic) UILabel * registLabel;
@property (strong, nonatomic) UILabel * forgetLabel;
@property (strong, nonatomic) UIView * lineView;
@property (strong, nonatomic) UIView * LIneView1;
@property (strong, nonatomic) UIView * leftLineView;
@property (strong, nonatomic) UIView * rightLineView;
@property (strong, nonatomic) UILabel * centerLabel;
@property (strong, nonatomic) UIButton * weiChatBtn;
@property (strong, nonatomic) UIButton * QQBtn;
@property (strong, nonatomic) UILabel * weChatLabel;
@property (strong, nonatomic) UILabel * QQLabel;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.phoneTextFiled.text = @"17722510228";
    self.passwordTextfiled.text = @"123456";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.img];
    [self.view addSubview:self.phoneTextFiled];
    [self.view addSubview:self.lineView];
    [self.view addSubview:self.passwordTextfiled];
    [self.view addSubview:self.LIneView1];
    [self.view addSubview:self.loadBtn];
    [self.view addSubview:self.registLabel];
    [self.view addSubview:self.forgetLabel];
    [self.view addSubview:self.leftLineView];
    [self.view addSubview:self.centerLabel];
    [self.view addSubview:self.rightLineView];
    [self.view addSubview:self.weiChatBtn];
    [self.view addSubview:self.QQBtn];
    [self.view addSubview:self.weChatLabel];
    [self.view addSubview:self.QQLabel];
}

-(UIView *)leftLineView
{
    if (_leftLineView == nil) {
        _leftLineView = [[UIView alloc] initWithFrame:CGRectMake(WIDTH/2 - 55, HEIGHT - kHomeLineH - 112.5, 21, 0.5)];
        _leftLineView.backgroundColor = SFMLineColor;
    }
    return _leftLineView;
}

-(UILabel *)centerLabel
{
    if (_centerLabel == nil) {
        _centerLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.leftLineView.frame), HEIGHT - kHomeLineH - 125, 68, 20)];
        _centerLabel.font = font(14);
        _centerLabel.textColor = SFM153;
        _centerLabel.textAlignment = NSTextAlignmentCenter;
        _centerLabel.text = @"or";
    }
    return _centerLabel;
}

-(UIView *)rightLineView
{
    if (_rightLineView == nil) {
        _rightLineView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.centerLabel.frame), HEIGHT - kHomeLineH - 112.5, 21, 0.5)];
        _rightLineView.backgroundColor = SFMLineColor;
    }
    return _rightLineView;
}

-(UIButton *)weiChatBtn
{
    if (_weiChatBtn == nil) {
        _weiChatBtn = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH/2 - 72.5, HEIGHT - kHomeLineH - 98, 45, 45)];
        [_weiChatBtn addTarget:self action:@selector(weiChatBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_weiChatBtn setImage:[UIImage imageNamed:@"weChatImg"] forState:UIControlStateNormal];
    }
    return _weiChatBtn;
}

#pragma mark - 微信点击事件
-(void)weiChatBtnClick:(UIButton *)btn
{
    SendAuthReq* req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    req.state = @"GUANGBAIPROPERTYAPP";
    [WXApi sendAuthReq:req viewController:self delegate:[WeiChatManager shareManager]];
    WeakSelf;
    [WeiChatManager shareManager].WeiChatDidLoginBlock = ^{
        NSSLog(@"微信登录成功=== ");
        //查询验证是否绑定信息
        [weakSelf judgeIsTiePhone];
    };
}

#pragma mark - 判断是否绑定手机号码
-(void)judgeIsTiePhone{
    
}

#pragma mark - 跳转实名认证
-(void)presentCtr{
    ReallyNameCertifyViewController * ctr = [[ReallyNameCertifyViewController alloc] init];
    ctr.isRegist = YES;
    UINavigationController * nvc = [[UINavigationController alloc] initWithRootViewController:ctr];
    [self presentViewController:nvc animated:YES completion:nil];
}

-(UIButton *)QQBtn
{
    if (_QQBtn == nil) {
        _QQBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.weiChatBtn.frame) + 55, HEIGHT - kHomeLineH - 98, 45, 45)];
        [_QQBtn addTarget:self action:@selector(qqBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_QQBtn setImage:[UIImage imageNamed:@"QQ"] forState:UIControlStateNormal];
    }
    return _QQBtn;
}

#pragma mark - qq点击事件
-(void)qqBtnClick:(UIButton *)btn
{
    self.oauth = [[TencentOAuth alloc] initWithAppId:@"101511062" andDelegate:self];
    NSMutableArray * permissions = [[NSMutableArray alloc] initWithObjects:kOPEN_PERMISSION_GET_USER_INFO,kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,kOPEN_PERMISSION_GET_INFO,nil]; //登录授权
    [self.oauth authorize:permissions inSafari:NO];
}

#pragma mark - qq 登录成功后的回调
- (void)tencentDidLogin
{
//    NSDictionary * dic = [self.oauth passData];
//    NSString * token = [self.oauth accessToken];
    NSString * openID = self.oauth.openId;
    [self.oauth getUserInfo];
    if (self.oauth.accessToken && 0 != [self.oauth.accessToken length])
    {
        [[HTTPClient shareClient] requestWithPath:@"/rest/appLoginController/qqLogin" AndParams:@{@"code":openID} AndReturnBlock:^(NSDictionary *dic) {
            
        } AndFailMessage:^(NSString *message, NSString *errorCode) {
            
        }];
    }
}

#pragma mark - QQ用户 登录失败主动取消登录 的回调
- (void)tencentDidNotLogin:(BOOL)cancelled
{
    
}

#pragma mark - QQ 登录时网络有问题的回调
- (void)tencentDidNotNetWork
{
    
}

#pragma mark -获取用户信息回调
- (void)getUserInfoResponse:(APIResponse*) response
{
    NSDictionary *message = response.jsonResponse;
    NSSLog(@"message=== %@",message);
//    message[@"nickname"];昵称
//    message[@"gender"]//性别
//    message[@"city"];//城市
//    message[@"year"];//出生年份
//    message[@"figureurl_1"]
//    message[@"figureurl_qq_1"]
    
    //查询验证是否绑定信息
    [self judgeIsTiePhone];
}

-(UILabel *)weChatLabel
{
    if (_weChatLabel == nil) {
        _weChatLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH/2 - 88.5, CGRectGetMaxY(self.weiChatBtn.frame) + 7, 75, 20)];
        _weChatLabel.font = font(12);
        _weChatLabel.textColor = SFMColor(102, 102, 102);
        _weChatLabel.textAlignment = NSTextAlignmentCenter;
        _weChatLabel.text = @"微信登录";
    }
    return _weChatLabel;
}

-(UILabel *)QQLabel
{
    if (_QQLabel == nil) {
        _QQLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.weChatLabel.frame) + 25, CGRectGetMaxY(self.weiChatBtn.frame) + 7, 75, 20)];
        _QQLabel.font = font(12);
        _QQLabel.textColor = SFMColor(102, 102, 102);
        _QQLabel.textAlignment = NSTextAlignmentCenter;
        _QQLabel.text = @"QQ登录";
    }
    return _QQLabel;
}

-(UIImageView *)img
{
    if (_img == nil) {
        _img = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH/2 - 17, kStatusAndNavBarH + 50, 57, 57)];
        _img.contentMode = UIViewContentModeScaleAspectFill;
        _img.clipsToBounds = YES;
        _img.image  = [UIImage imageNamed:@"logo"];
    }
    return _img;
}

-(UITextField *)phoneTextFiled
{
    if (_phoneTextFiled == nil) {
        _phoneTextFiled = [[UITextField alloc]initWithFrame:CGRectMake(45, CGRectGetMaxY(self.img.frame) + 25, WIDTH - 90, 30)];
        _phoneTextFiled.placeholder = @"请输入手机号";
        _phoneTextFiled.font = font(16);
        _phoneTextFiled.textColor = SFMColor(51, 51, 51);
        _phoneTextFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneTextFiled.keyboardType = UIKeyboardTypeNumberPad;
        [_phoneTextFiled addTarget:self action:@selector(telPhoneTextChang) forControlEvents:UIControlEventEditingChanged];
    }
    return _phoneTextFiled;
}

-(void)telPhoneTextChang
{
    NSString * str = _phoneTextFiled.text;
    if (str.length>11) {
        _phoneTextFiled.text = [str substringToIndex:11];
    }
}

-(UIView *)lineView
{
    if (_lineView == nil) {
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(42, CGRectGetMaxY(self.phoneTextFiled.frame) + 10, WIDTH - 84, 0.5)];
        _lineView.backgroundColor = SFMLineColor;
    }
    return _lineView;
}

-(UITextField *)passwordTextfiled
{
    if (_passwordTextfiled == nil) {
        _passwordTextfiled = [[UITextField alloc]initWithFrame:CGRectMake(45, CGRectGetMaxY(self.lineView.frame)+25, WIDTH - 90, 30)];
        _passwordTextfiled.placeholder = @"请输入密码";
        _passwordTextfiled.font = font(16);
        _passwordTextfiled.textColor = SFMColor(51, 51, 51);
        [_passwordTextfiled addTarget:self action:@selector(pwdTextfiledDidChange) forControlEvents:UIControlEventEditingChanged];
        _passwordTextfiled.secureTextEntry = YES;
    }
    return _passwordTextfiled;
}

-(void)pwdTextfiledDidChange
{
    NSString * str = self.passwordTextfiled.text;
    if (str.length > 18) {
        self.passwordTextfiled.text = [str substringToIndex:18];
    }
}

-(UIView *)LIneView1
{
    if (_LIneView1 == nil) {
        _LIneView1 = [[UIView alloc] initWithFrame:CGRectMake(42, CGRectGetMaxY(self.passwordTextfiled.frame) + 10, WIDTH - 84, 0.5)];
        _LIneView1.backgroundColor = SFMLineColor;
    }
    return _LIneView1;
}

-(UIButton *)loadBtn
{
    if (_loadBtn == nil) {
        _loadBtn = [[UIButton alloc] initWithFrame:CGRectMake(22.50, CGRectGetMaxY(self.LIneView1.frame)+25, WIDTH-45, 50)];
        _loadBtn.titleLabel.font = font(16);
        _loadBtn.layer.cornerRadius = 25;
        [_loadBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loadBtn setBackgroundColor:SFMNavBarColor];
        [_loadBtn addTarget:self action:@selector(loadBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loadBtn;
}

#pragma mark - 登录事件
-(void)loadBtnClick:(UIButton *)btn
{
    [self.view endEditing:YES];
    NSString * phone = self.phoneTextFiled.text;
    NSString * pwd = self.passwordTextfiled.text;
    
    if (phone.length !=11) {
        [MBProgressHUD showMessageWithDelay:@"手机号码格式有误" delay:2];
        return;
    }
    
    if (pwd.length < 6) {
        [MBProgressHUD showMessageWithDelay:[NSString stringWithFormat:@"密码长度至少%d位",6] delay:2];
        return;
    }
    
    if ([NSString valiMobile:phone]) {
        
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        [params setValue:phone forKey:@"username"];
        [params setValue:pwd forKey:@"password"];
        
        WeakSelf;
        [[HTTPClient shareClient] requestWithPath:@"/rest/appLoginController/getToken" AndParams:params AndReturnBlock:^(NSDictionary *dic) {
            [SVProgressHUD ShowSuccessMessage:@"登陆成功"];
            NSDictionary * dics = dic[@"data"];
            NSString * token = dics[@"token"];
            NSDictionary * dicss = dics[@"user"];
            NSString * loginname = dicss[@"username"];
            NSString * headimgurl = dicss[@"headimgurl"];
            NSString * gbuserid = dicss[@"gbuserid"];
            NSString * usertype = dicss[@"usertype"];
            NSString * userID = dicss[@"id"];

            [[NSUserDefaults standardUserDefaults] setValue:token forKey:@"token"];
            [[NSUserDefaults standardUserDefaults] setValue:loginname forKey:@"loginname"];
            [[NSUserDefaults standardUserDefaults] setValue:headimgurl forKey:@"headimgurl"];
            [[NSUserDefaults standardUserDefaults] setValue:gbuserid forKey:@"gbuserid"];
            [[NSUserDefaults standardUserDefaults] setValue:usertype forKey:@"usertype"];
            [[NSUserDefaults standardUserDefaults] setValue:userID forKey:@"Id"];

            [[NSUserDefaults standardUserDefaults] synchronize];
            
            
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
                NSString *path=[docPath stringByAppendingPathComponent:@"person.archiver"];
                NSMutableArray * arr = [NSMutableArray array];
                for (NSDictionary * authListDic in dics[@"authList"]) {
                    authListModel * model = [authListModel modelWithDic:authListDic];
                    [arr addObject:model];
                }
                [NSKeyedArchiver archiveRootObject:arr toFile:path];
                weakSelf.DidLoginEventBlock();
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            });
        }AndFailMessage:^(NSString *message, NSString *errorCode) {
            [MBProgressHUD showMessageWithDelay:message delay:2];
        }];
    }else
    {
        [MBProgressHUD showMessageWithDelay:@"手机号码格式有误" delay:2];
        return;
    }
}

-(UILabel *)registLabel
{
    if (_registLabel == nil) {
        _registLabel =[[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2 - 65, CGRectGetMaxY(self.loadBtn.frame) + 25, 50, 20)];
        _registLabel.font =font(14);
        _registLabel.textColor=SFMColor(255, 55, 88);
        _registLabel.textAlignment=NSTextAlignmentCenter;
        _registLabel.text = @"注册";
        _registLabel.userInteractionEnabled = YES;
        [_registLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(registLabelTap)]];
    }
    return _registLabel;
}

-(UILabel *)forgetLabel
{
    if (_forgetLabel == nil) {
        _forgetLabel =[[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2-15, CGRectGetMaxY(self.loadBtn.frame) + 25, 100, 20)];
        _forgetLabel.font =font(14);
        _forgetLabel.textColor=SFMColor(51, 51, 51);
        _forgetLabel.textAlignment=NSTextAlignmentLeft;
        _forgetLabel.text = @"｜   忘记密码";
        _forgetLabel.userInteractionEnabled = YES;
        [_forgetLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(forgetLabelTap)]];
    }
    return _forgetLabel;
}

#pragma mark - 注册
-(void)registLabelTap
{
    RegistViewController * ctr = [[RegistViewController alloc] init];
    [self presentViewController:ctr animated:YES completion:nil];
}

-(void)forgetLabelTap
{
    ForgetPassWordViewController * ctr = [[ForgetPassWordViewController alloc] init];
    UINavigationController * nvc = [[UINavigationController alloc] initWithRootViewController:ctr];
    [self presentViewController:nvc animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
